var app = getApp();
const utils = require('../../../utils/util.js');
var wxpay = require('../../../utils/pay.js');
var chat = require('../../../utils/chat.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTitleText: '',
    goodsResult: [],
    goodsResultOff: [],
    cardInfo: {},
    showmsg: true, //判断是否是自己
    scrollHeight: "",
    scrollTop: 0,
    classList: [],
    CurrentPage: 1,
    loadingMoreHidden: 1,
    CurrentPageOff: 1,
    loadingMoreHiddenOff: 1,
    isOff: false,
    selectedMenuId: 0,
    cateId: 0, //产品标签
    groupId: 0, //195其他分类,375 代金券商品, 376 套餐商品
    Word: '',
    proSkulist: {}, //选中的规格名称、价格、ID
    skuBycount: 0,  //规格商品的购买数量
    showDialog: false,
    cartResult: {StoreCartList:[]}, //购物车
    cartNumber: 0,
    cartSumPrice: 0,  
    pname: '',
    price: '',
    isShowCart: true,
    userInfo: {},
    versionid: 4,
    payDialog: { //代支付弹框
      isshow: false,
      ispay: false,
      title1: "",
      title2: "",
      submittext: ""
    },
    showmenu: false,
    msgLength: 0,
    fromuid: 0,
    x: 300,
    y: 360,
    x2: 0,
    screenHeight: 500,
    navBarHeight: 44,
    hasGoodsOff: false,
    loginCode: '',
    lastPrice: 0,
    isAccredit: true,
    canIUseGetUserProfile: false,
    isFriendState: 0, //0 非分享, 1 朋友圈分享 
    supplyUid: 0,      //供货商家id
    couponTypeList: [], //商家优惠券列表
    topCoupons:[],  //顶部的优惠券
    isPackage: 0,   //优惠券是否是礼包
    isCoupon: false, //优惠券弹框 
  },

  // 标签管理
  labelManage: function () {
    wx.navigateTo({
      url: '/order/order/labelManage/index',
    })
  },

  // 联系商家
  makeCallPhone: function () {
    let mobile = this.data.cardInfo.CardInfo.Mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  },

  // 优惠券抢购
  addCouponCart: function (e) { 
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let stock = e.currentTarget.dataset.stock;
    if (stock < 1) {
      utils.showToast('商品库存不足');
      return;
    }
    if(!that.isLogin()){
      return;
    }
    that.clearCart(function (flag) {
      if (flag) { //清空购物车完成
        wx.request({
          url: app.globalData.host + '/api/cart/AddProduct',
          data: {
            uid: app.globalData.userInfo.Uid,
            pid: pid,
            buyCount: 1,
            optionIds: '',
            createUid: that.data.cardInfo.CardInfo.Uid
          },
          success: function (res) {
            if (res.data.Code == 0) {
              // 跳转优惠券购物车页面
              wx.navigateTo({
                url: '/order/order/cart/index?isCoupon=1&stockNumber=' + stock,
              })
            } else {
              utils.showModal(res.data.Message);            
            }
          }
        })
      }
    })
  },

  // 清空购物车
  clearCart: function (cb) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Cart/Clear?uid=' + app.globalData.userInfo.Uid + '&createUid=' + that.data.cardInfo.CardInfo.Uid,
      success: function (res) {
        cb(res.data.Data);
      }
    })
  },

  addShopCarSku: function () {
    let that = this;
    let pid = that.data.proSkulist.pid;
    let cartResult = that.data.cartResult;   
    if (app.globalData.isFriendState == 1) {     
      utils.showToast('请前往小程序使用完整服务');
      return;
    }
    if(!that.isLogin()){
      return;
    }
         
    if (cartResult.StoreCartList.length > 0) {
      let list = cartResult.StoreCartList[0].CartProductList;
      let hasCouPro = false;
      for (let i = 0; i < list.length; i++) {
        if (list[i].OrderProductInfo.CateId == 376 || list[i].OrderProductInfo.CateId == 375) {
          hasCouPro = true;
          break;
        }
      }
      if (hasCouPro) {
        that.clearCart(function (flag) {
          if (flag) { //清空购物车完成
            that.addShopCarSkuConfirm(pid)
          }
        })
      } else {
        that.addShopCarSkuConfirm(pid)
      }
    } else {
      that.addShopCarSkuConfirm(pid)
    }
    //关闭弹框
    that.closeSkudialog();
  },

  addShopCarSkuConfirm: function (pid) {
    let that = this;
    let skuBycount = that.data.skuBycount;
    // let supplyUid = that.data.supplyUid;
    let path =  app.globalData.diningSid != 0 ?  '/api/cart/AddSessionProduct' : '/api/cart/AddProduct';
    let optionIds = that.getOptionids(pid);
    let data = {
      uid: app.globalData.userInfo.Uid,
      pid: pid,
      buyCount: 1,
      optionIds: optionIds,
      sid: app.globalData.diningSid,
      //createUid: supplyUid > 0 ? supplyUid : that.data.cardInfo.CardInfo.Uid,
      createUid: that.data.createUid,
      saleUid: that.data.supplyUid > 0 ? that.data.cardInfo.CardInfo.Uid : 0
    };
    //清空上一次选中规格
    that.data.proSkulist.optionIds = ''; 
    wx.request({
      url: app.globalData.host + path,
      data: data,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCart(that.data.goodsResult);
          that.setData({
            skuBycount: skuBycount + 1,
            isShowCart: true
          });    
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  jianShopCarSku: function () {
    var that = this;
    var pid = that.data.proSkulist.pid;
    let skuBycount = parseInt(that.data.skuBycount);
    let optionIds = that.getOptionids(pid);
    let data = {
      uid: app.globalData.userInfo.Uid,
      pid: pid,
      buyCount: skuBycount - 1 > 0 ? skuBycount - 1 : 0,
      selList: '0_' + pid,
      optionIds: optionIds,
      createUid: that.data.cardInfo.CardInfo.Uid,
      sid: app.globalData.diningSid
    }
    let path =  app.globalData.diningSid != 0 ? '/api/cart/ChangeSessionProductCount' : '/api/cart/ChangeProductCount';
    wx.request({
      url: app.globalData.host + path,
      data: data,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCart(that.data.goodsResult);
          that.setData({
            skuBycount: skuBycount - 1,
            isShowCart: true
          });
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },

  // 弹出选规格弹窗
  chooseSku: function (e) {
    let that = this;
    let optionids = e.currentTarget.dataset.optionids;
    let pname = e.currentTarget.dataset.pname;
    let price = e.currentTarget.dataset.price;
    let pid = e.currentTarget.dataset.pid;
    let stock = e.currentTarget.dataset.stock;
    let count = e.currentTarget.dataset.count;
    let skuBycount = 0;
    if (stock <= count) {
      utils.showModal('商品库存不足');
      return;
    }
    if(!that.isLogin()){
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionList?optionIds=' + optionids,
      success: function (res) {
        if (res.data.Code == 0) {
          let proSkulist = {};
          proSkulist.pid = 0;
          proSkulist.optionIds = '';  //当前选择的规格
          proSkulist.selectSkuname = '';
          proSkulist.optionPrice = 0;
          proSkulist.list = res.data.Data;
          for (let i = 0; i < proSkulist.list.length; i++) {
            proSkulist.list[i].selOptionid = proSkulist.list[i].OptionList[0].OptionId;
            proSkulist.list[i].selOptionName = proSkulist.list[i].OptionList[0].Name;
            proSkulist.list[i].selOptionPrice = proSkulist.list[i].OptionList[0].Price;       
            proSkulist.list[i].pid = pid; 
          }

          let lastPrice = price + proSkulist.optionPrice;
          that.setData({
            proSkulist: proSkulist,
            showDialog: !that.data.showDialog,
            pname: pname,
            lastPrice: lastPrice,
            price: price,
            skuBycount: skuBycount
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  
  selectSku: function (e) {
    let that = this;
    let optionid = e.currentTarget.dataset.optionid;
    let tagid = e.currentTarget.dataset.tagid;
    let price = that.data.price;
    let skuBycount = 0;
    let cartResult = that.data.cartResult;
    let proSkulist = that.data.proSkulist;
    proSkulist.pid = 0;
    proSkulist.optionIds = ''; 
    proSkulist.selectSkuname = '';
    proSkulist.optionPrice = 0;

    for (let i = 0; i < proSkulist.list.length; i++) {
      let tag = proSkulist.list[i];//规格
      if(tagid == tag.TagId){
        //规格选项
        for(var j = 0;j <tag.OptionList.length; j++){
          if(tag.OptionList[j].isSelect == null){
            tag.OptionList[j].isSelect = false;
          }
          if(tag.IsMultiple){
            if(tag.OptionList[j].OptionId == optionid){
              tag.OptionList[j].isSelect = !tag.OptionList[j].isSelect;   //多选
            }
          }else{                       
            if(tag.OptionList[j].OptionId == optionid){
              tag.OptionList[j].isSelect = !tag.OptionList[j].isSelect;   //单选
            }else{
              tag.OptionList[j].isSelect = false;
            }
          }  
        }
      }    
    }
    //选中的规格
    for (let i = 0; i < proSkulist.list.length; i++) {
      var tag = proSkulist.list[i]
      for(var j = 0;j < tag.OptionList.length; j++){
        if(tag.OptionList[j].isSelect){
          proSkulist.pid = tag.pid;
          proSkulist.optionIds += proSkulist.optionIds !='' ? ',' : '';
          proSkulist.optionIds += tag.OptionList[j].OptionId;
          proSkulist.selectSkuname +=  proSkulist.selectSkuname!='' ? '、': '';
          proSkulist.selectSkuname += tag.OptionList[j].Name;
          proSkulist.optionPrice += tag.OptionList[j].Price;
        }
      }
    }
    //已加入购物车的数据
    let productList = cartResult.StoreCartList.length>0 ? cartResult.StoreCartList[0].CartProductList : [];
    for (let i = 0; i < productList.length; i++) {
      let p = productList[i].OrderProductInfo;
      if (p.OptionIds == proSkulist.optionIds && p.Pid == proSkulist.pid) {
        skuBycount = p.BuyCount;  //购物车数量
      }
    }
    
    that.setData({
      proSkulist: proSkulist,
      skuBycount: skuBycount,
      price: parseFloat(price).toFixed(2),
      lastPrice: (parseFloat(price) + proSkulist.optionPrice).toFixed(2)
    })    
  },

  addShopCar: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let stock = e.currentTarget.dataset.stock;
    let currentbuynum = e.currentTarget.dataset.buynum;
    let cartResult = that.data.cartResult;
    if (app.globalData.isFriendState == 1) {
      utils.showToast('请前往小程序使用完整服务');  
      return;
    }
    if(!that.isLogin()){
      return;
    }
    if (stock <= currentbuynum) {
      utils.showModal('商品库存不足'); return;
    }
    if (cartResult.StoreCartList.length > 0) {
      let list = cartResult.StoreCartList[0].CartProductList;
      let hasCouPro = false;
      for (let i = 0; i < list.length; i++) {
        if (list[i].OrderProductInfo.CateId == 376 || list[i].OrderProductInfo.CateId == 375) {
          hasCouPro = true;
          break;
        }
      }
      if (hasCouPro) {
        that.clearCart(function (flag) {
          if (flag) { //清空购物车完成
            that.addShopCarConfirm(pid);
          }
        })
      } else {
        that.addShopCarConfirm(pid);
      }
    } else {
      that.addShopCarConfirm(pid);
    }
  },
  addShopCarConfirm: function (pid) {
    let that = this;
    // let supplyUid = that.data.supplyUid;
    let path =  app.globalData.diningSid != 0 ?  '/api/cart/AddSessionProduct' : '/api/cart/AddProduct';
    let optionIds = that.getOptionids(pid);
    let data = {
      uid: app.globalData.userInfo.Uid,
      pid: pid,
      buyCount: 1,
      optionIds: optionIds,
      sid: app.globalData.diningSid,
      // createUid: supplyUid > 0 ? supplyUid : that.data.cardInfo.CardInfo.Uid,
      createUid: that.data.createUid,
      saleUid: that.data.supplyUid > 0 ? that.data.cardInfo.CardInfo.Uid : 0
    };
   
    wx.request({
      url: app.globalData.host + path,
      data: data,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({isShowCart: true})
          that.getCart(that.data.goodsResult);
          utils.showToast('加入购物车成功','success');         
        } else {
          utils.showModal(res.data.Message);       
        }
      }
    })
  },
  jianShopCar: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.pid;
    let price = e.currentTarget.dataset.shopprice;
    let cartNumber = that.data.cartNumber;
    let cartSumPrice = that.data.cartSumPrice;
    let goodsResult = that.data.goodsResult;
    let upcount = 1;
    for (let i = 0; i < goodsResult.length; i++) {
      if (goodsResult[i].Pid == pid) {
        goodsResult[i].currentBuynum = goodsResult[i].currentBuynum - 1;
        upcount = goodsResult[i].currentBuynum;
        cartSumPrice -= price;
        cartNumber -= 1;
        break;
      }
    }

    let data = {
      uid: app.globalData.userInfo.Uid,
      pid: pid,
      buyCount: upcount,
      selList: '0_' + pid,
      createUid: that.data.cardInfo.CardInfo.Uid,
      sid: app.globalData.diningSid
    }
    let path = app.globalData.diningSid != 0 ? '/api/cart/ChangeSessionProductCount' : '/api/cart/ChangeProductCount';
    wx.request({
      url: app.globalData.host + path,
      data: data,
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            isShowCart: true,
            goodsResult: goodsResult,
            cartNumber: cartNumber,
            cartSumPrice: parseFloat(cartSumPrice).toFixed(2)
          });
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },

  //获取选中的optionId
  getOptionids: function(pid){
    let that = this;
    let proSkulist = that.data.proSkulist;
    if(proSkulist.pid == pid){
      return proSkulist.optionIds;
    }
    return '';
  },
  bindGoods: function(goodsResult) {  
    for (let j = 0; j < goodsResult.length; j++) {
      let item = goodsResult[j];    
      if (item.ShowImg.indexOf('ps') != -1) {
        item.ShowImg = utils.formatAvaterByProHead(item.ShowImg);
      } else {
        item.ShowImg = utils.formatAvater(item.ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
      }
      if (item.SendEndTime.indexOf('1970') != -1) {
        item.ExpireTime = '';
      } else {
        item.ExpireTime = item.SendEndTime.substr(0, 10);
        item.ExpireTime = item.ExpireTime.replace(/\//g, "-");
      }
      item.currentBuynum = item.currentBuynum>0 ? item.currentBuynum : 0;
    }
    return goodsResult;
  },
  getCart: function (goodsResult) {
    let that = this;
    let path  = app.globalData.diningSid != 0 ?  '/api/Cart/SessionIndex' : '/api/Cart/Index';
    if(!that.data.createUid || !app.globalData.userInfo) {
      return;
    }
    wx.request({
      url : app.globalData.host + path,
      data: {
        createUid: that.data.createUid,
        uid: app.globalData.userInfo.Uid, 
        sid: app.globalData.diningSid
      },
      success: function (res) {
        if(res.data.Code != 0){
          utils.showModal(res.data.Message); 
          return;
        } 
        let cartResult = res.data.Data;
        if (cartResult.StoreCartList.length > 0) {
          let checkList = cartResult.StoreCartList[0].CartProductList;
          for (let m = 0; m < checkList.length; m++) {
            for (let i = 0; i < goodsResult.length; i++) {
              if (goodsResult[i].Pid == checkList[m].OrderProductInfo.Pid) {
                goodsResult[i].currentBuynum = checkList[m].OrderProductInfo.RealCount;
              }
            }
          }
        }
        that.data.cartResult = cartResult;
        that.setData({
          goodsResult: goodsResult,
          cartNumber: cartResult.TotalCount,
          cartSumPrice: cartResult.ProductAmount,
        })
      }
    })
  },

  closeSkudialog: function () {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  // 下架产品
  selectOff: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.indexid;
    let cid = e.currentTarget.dataset.cid;
    let gid = e.currentTarget.dataset.gid;
    that.data.CurrentPageOff = 1;
    that.data.cateId = cid;
    that.data.gid = gid;
    that.data.isOff = true;
    that.setData({
      selectedMenuId: index,
      goodsResult: []
    })
    that.searchGoodsOff();
  },

  // 选择菜单分类
  selectMenu: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.indexid;
    let cid = e.currentTarget.dataset.cid;    
    
    that.setData({
      CurrentPage: 1,
      cateId: cid,
      groupId: e.currentTarget.dataset.gid,
      selectedMenuId: index,
      goodsResultOff: [],
      goodsResult: []
    })

    //云点单分类特殊处理
    let version = e.currentTarget.dataset.layer;  //5 云点单版, 6云带货版
    if(version=='5' || version =='6'){
      let model = that.data.showmsg ? 2 : 1; //1 编辑模式(可管理自己的供货商), 2 下单模式(用户下单购买模式)
      wx.navigateTo({
        url: '/merchant/supply/list/index?createUid=' + that.data.cardInfo.CardInfo.Uid + '&model=' + model + '&version=' + version,
      })
      return;
    }           
    that.searchGoods();
  },

  toCart: function (e) {
    let that = this;
    let cartNumber = this.data.cartNumber;
    let name = e.currentTarget.dataset.bossname;
    let isCoupon = 0;
    if (cartNumber > 0) {
      let list = this.data.cartResult.StoreCartList[0].CartProductList;
      for (let i = 0; i < list.length; i++) {
        if (list[i].OrderProductInfo.CateId == 375 || list[i].OrderProductInfo.CateId == 376) {
          isCoupon = 1;
          break;
        }
      }
      // let createUid = that.data.supplyUid > 0 ? that.data.supplyUid : that.data.cardInfo.CardInfo.Uid; 
      let saleUid = that.data.supplyUid > 0 ? that.data.cardInfo.CardInfo.Uid : 0;
      let url =  app.globalData.diningSid != 0 ?  '/order/order/SessionCart/index' : '/order/order/cart/index';
      wx.navigateTo({
        url: url + '?bossname=' + name + '&isCoupon=' + isCoupon + '&seltoid=' + that.data.createUid + '&saleUid=' + saleUid
      });
    } else {
      utils.showToast('购物车没有商品');
    }
  },

  toDetailsTap: function (e) {
    var that = this
    var pid = e.currentTarget.dataset.id;
    var cardInfo = that.data.cardInfo.CardInfo;
    var url = '/pages/productDetails/index?pid=' + pid;
    if(that.data.supplyUid > 0){
      url +='&seltoid=' + that.data.supplyUid +'&saleUid=' + cardInfo.Uid + "&name=" + cardInfo.Name;
    }else{
      url += "&seltoid=" + cardInfo.Uid + '&hasSaleUid=1' + "&name=" + cardInfo.Name;  //hasSaleUid: 1没有卖券商家uid,2有卖券商家Uid
    }
    wx.navigateTo({url: url})
  },

  editorProduct: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let cardInfo = this.data.cardInfo.CardInfo;
    wx.navigateTo({
      url: '/pages/weijieke/product/index?pid=' + pid + '&backpage=index' + '&seltoid=' + cardInfo.Uid + '&industryCode='+ cardInfo.IndustryCode,
    })
  },

  //是否带编辑功能
  showMessege: function (cardInfo) {
    var cardInfo = cardInfo.CardInfo;
    var showmsg = true;
    if(app.globalData.userInfo){
      showmsg = app.globalData.userInfo.Uid == cardInfo.Uid ? false : true;
    }
    //云点单特殊处理
    if(this.data.supplyUid > 0){
      showmsg = this.data.supplyUid == cardInfo.Uid ? false : true;
    }
    this.setData({
      showmsg: showmsg
    })
  },

  // 获取名片信息
   getAiCardInfo: function () {
    let that = this;
    let createUid = that.data.createUid;
    let cardId = wx.getStorageSync("cardId");
    if (!cardId) {
      utils.showToast('加载失败请重试'); 
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaff?id=' + cardId,
      success: function (res) {
        let cardInfo = res.data.Data;
        if(res.data.Code !=0){
          utils.showModal(res.data.Message);        
          return;
        }        
       //升级弹框
        if (cardInfo.IndustryCode == 1){
          that.showPayDialog(); 
          return;  
        }

        that.setData({
          cardInfo: {CardInfo: cardInfo},
          createUid: createUid > 0 ? createUid: cardInfo.Uid 
        });
        that.showMessege(that.data.cardInfo);
        that.getGoodsClassList();
        that.searchGoods();
        if(app.globalData.isFriendState != 1){
          that.hasGoodsOff();
        }
        utils.getMsgUnRead(cardInfo.Uid, function (msgLength) {
          that.setData({msgLength: msgLength})
        });
      }
    })
  },

  //升级弹框
  showPayDialog: function () {
    let payDialog = this.data.payDialog;
    payDialog.isshow = true;
    payDialog.ispay = true,
    payDialog.title1 = "升级后才能使用该功能";
    payDialog.submittext = "立即升级";           
    if (app.globalData.platform == 'ios') {
      payDialog.ispay = false;
      payDialog.title1 = "升级后才能使用该功能";
      payDialog.submittext = "发送升级申请";
    }
    this.setData({
      payDialog: payDialog
    })
  },
  // 是否有下架产品
  hasGoodsOff: function () {
    let that = this;
    let cardInfo = that.data.cardInfo.CardInfo;
    if(that.data.supplyUid > 0){
      return; //显示供货商家的商品时，不需要获取本商家下架商品
    }
    wx.request({
      url: app.globalData.host + '/api/store/Search',
      data: {
        storeId: app.globalData.storeId,
        groupId: 0,
        cateId: that.data.cateId,
        addUid: cardInfo.Uid,
        page: 1,
        word: '',
        isExtend: 1,
        state: 1
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.ProductList && res.data.Data.ProductList.length > 0) {
            that.setData({hasGoodsOff: true})
          }
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },

  //关闭注册玖玖客弹框
  dialogsState: function () {
    let {
      payDialog
    } = this.data;
    if (payDialog.isshow) {
      payDialog.isshow = false;
    } else {
      payDialog.isshow = true;
    }
    this.setData({
      payDialog: payDialog
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('产品',options)
    var that = this;
    if (options.id) {
      wx.setStorageSync('cardId', options.id);
    }   
    //扫码普通二维码   
    if (options.q) {
      var url = decodeURIComponent(options.q); 
      var cardId = utils.getQuery(url,'id');
      var lineType= utils.getQuery(url,'lineType'); //配送方式: 1 线上订单,2 自提订单
      wx.setStorageSync('cardId', cardId);
      wx.setStorageSync('shipInfo', {cardId: cardId, showAdress: lineType == 2});  
    }
    //供货商ID,带此参时只显示商家的供货商品
    if(options.supplyUid){
      wx.setStorageSync('supplyUid', options.supplyUid);
      wx.setStorageSync('supplyVersion', options.version);
      that.setData({
        supplyUid: options.supplyUid,
        createUid: options.supplyUid
      })
    }else{
      wx.removeStorageSync('supplyUid');
      wx.removeStorageSync('supplyVersion');
    }
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        })
      }
    })
    let info = wx.getSystemInfoSync();
    var screenHeight = info.screenHeight - 130;
    let screenWidth = info.screenWidth - 75;
    that.setData({
      screenHeight: screenHeight,
      x: screenWidth,
      navBarHeight: app.globalData.navBarHeight
    })
    if (app.globalData.isFriendState == 1) {
      that.setData({isFriendState: 1})
      that.getAiCardInfo(app.globalData.friendUid);
      return;
    }
    //是否需要授权昵称头像
    utils.isAccredit(function (isAccredit) {
      that.data.isAccredit = isAccredit;
    });
    if (wx.getUserProfile) {
      that.setData({canIUseGetUserProfile: true})
    }
    let showIndex = wx.getStorageSync('showIndex');
    if (showIndex == '/pages/classes-new/index') {
      that.toChat();
      wx.login({
        success: (res) => {
          that.setData({
            loginCode: res.code
          })
        },
      })
      that.setData({
        showmenu: true
      })
    }
    //名片信息
    that.getAiCardInfo();
  },

  onShow: function () {
    var that = this;
    if (that.data.imgsrc) {
      that.staffAvatarUpload(that.data.imgsrc);
    }
    if (app.globalData.userInfo) {      
      that.GetIndexCoupon();
      utils.aiCardActionRecord(0);
    } else {
      setTimeout(() => {
        that.onShow()
      }, 1000);
    }

  },

  // 上架商品 
  searchGoods: function () {
    let that = this;  
    let groupId = that.data.groupId;
    if (app.globalData.diningSid != 0) {
      groupId = 195;
    }
    wx.showLoading({title: '加载中'})
    wx.request({
      url: app.globalData.host + '/api/product/list',
      data: {
        storeId: app.globalData.storeId,
        groupId: groupId,         //195单品375优惠券376套餐
        cateId: that.data.cateId, //产品标签
        addUid: that.data.createUid,
        page: that.data.CurrentPage,
        word: that.data.Word,
        isExtend: 1,
        state: 0,
        saleUid: that.data.cardInfo.CardInfo.Uid   //共享带货:带货人id
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var products = that.bindGoods(res.data.Data.ProductList);
          if (that.data.CurrentPage != 1) {
            products = that.data.goodsResult.concat(products);
          }
          that.getCart(products);
          that.setData({
            goodsResult: products,
            loadingMoreHidden: res.data.Data.PageModel.TotalPages,
          });
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  // 下架商品
  searchGoodsOff: function () {
    var that = this;
    let state = 1;
    let CurrentPageOff = that.data.CurrentPageOff;
    let cardInfo = that.data.cardInfo.CardInfo;
    wx.request({
      url: app.globalData.host + '/api/store/Search',
      data: {
        storeId: app.globalData.storeId,
        groupId: 0,
        cateId: that.data.cateId,
        addUid: cardInfo.Uid,
        page: CurrentPageOff,
        word: that.data.Word,
        isExtend: 1,
        state: state
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var data = res.data.Data;
          var products = that.bindGoods(data.ProductList);
          if (that.data.CurrentPageOff != 1) {
            var preGoods = that.data.goodsResultOff;
            products = preGoods.concat(products);
          }          
          that.setData({
            goodsResultOff: products,
          });
          that.data.loadingMoreHiddenOff = data.PageModel.TotalPages;
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },

  loadMore: function (e) {
    let that = this;
    let currPage = that.data.CurrentPage;
    let currPageOff = that.data.CurrentPageOff;
    console.log('下拉');
    if (that.data.isOff) { //下架商品
      if (that.data.loadingMoreHiddenOff > 1 && currPageOff < that.data.loadingMoreHiddenOff) {
        that.data.CurrentPageOff = currPageOff + 1;
        that.searchGoodsOff();
      } else {
        return
      }
    } else { //上架商品
      if (that.data.loadingMoreHidden > 1 && currPage < that.data.loadingMoreHidden) {
        that.setData({
          CurrentPage: currPage + 1
        })
        that.searchGoods();
      } else {
        return
      }
    }
  },
  //sku产品去重
  checkProduct: function (products, text) {
    var state = false; //默认不存在
    if (products.length > 0 && text != 0) {
      if (products.length > 0) {
        for (var i = 0; i < products.length; i++) {
          if (text == products[i].SKUGid) {
            state = true; //已经存在
            break;
          }
        }
      }
    }
    return state;
  },

  /** 点击完成按钮是触发 */
  handleConfirm: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 搜索框失去焦点是触发 */
  handleBlur: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  /** 取消搜索 */
  handleCancel: function (e) {
    this.setData({
      Word: ''
    })
  },
  handleInput: function (e) {
    this.setData({
      Word: e.detail.value
    })
  },
  handleSearchWord: function (e) {
    this.setData({
      CurrentPage: 1,
      loadingMoreHidden: 1,
      selCatId: 0,
      selCatName: '',
      selBrandId: 0,
      selBrandName: '',
      selPriceId: 0,
      selPriceName: '',
      isCategoryTap: false,
      isBrandTap: false,
      isPriceTap: false,
      showSearch: false,
      searchCategory: [], //当前搜索类型
      goodsResult: [],
      goodsResultOff: [],
      CurrentPageOff: 1,
      loadingMoreHiddenOff: 1
    })
    this.searchGoods();
  },

  //获取商品分类列表
  getGoodsClassList: function () {
    var that = this;
    // let uid = that.data.supplyUid > 0 ? that.data.supplyUid : that.data.cardInfo.CardInfo.Uid;
    wx.request({
      url: app.globalData.host + '/api/Store/GetStoreClassList?storeId=' + app.globalData.storeId + "&uid=" + that.data.createUid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            var list = res.data.Data;
            var newList = [];
            var other = [];
            for (let i = 0; i < list.length; i++) {
              if (list[i].StoreCid == 48917) {
                other = list[i];
              } else {
                newList.push(list[i])
              }
            }
            newList = newList.concat(other);
            that.setData({
              classList: newList
            })
          }
        } else {
          utils.showModal(res.data.Message);          
        }
      },
    })
  },

//获取优惠券
GetIndexCoupon: function(){
  var that = this;
  //供货商优惠券
  if(that.data.supplyUid > 0){
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffIdByUid?uid=' + that.data.supplyUid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.GetCoupon(res.data.Data.Id);
        } 
      },
    })
  } 
  else{
    //商家优惠券
    var cardId = wx.getStorageSync("cardId");
    that.GetCoupon(cardId)
  }
},

//首页优惠券
GetCoupon: function(cardId){
  let that = this;    
  wx.request({
    url: app.globalData.host + '/api/staff/GetIndexCoupon?type=10&staffId='+ cardId + '&uid=' + app.globalData.userInfo.Uid,
    success: function (res) {
      if (res.data.Code == 0) {
        var couponTypeList = res.data.Data.CouponTypeList;         
        that.setData({
          isPackage: res.data.Data.IsPackage,
          couponTypeList: couponTypeList,
          topCoupons: couponTypeList.slice(0,3),
        })
      } else {
        utils.showModal(res.data.Message);          
      }
    },
  })
},

  //获取输入框的值
  getValueInput: function (e) {
    let labelName = e.detail.value;
    this.setData({
      labelName: labelName
    })
  },

  // 根据底部导航显示标题
  tabbareventListener: function (e) {
    let title = utils.getNavBarTitle(e, "/pages/classes-new/index");
    this.setData({
      navTitleText: title
    })
  },

  tapChatFrom: function () {
    if (this.data.cardInfo.CardInfo) {
      utils.tapChatFrom(this.data.cardInfo.CardInfo);
    }
  },

  //监听用户滑动页面事件
  bindscroll: function (e) {
    let scrollTop = parseInt(e.detail.scrollTop);
    let showmenu = this.data.showmenu;
    this.setData({
      scrollTop: scrollTop,
      isShowCart: false,
      showmenu: false
    })
    let timer = setTimeout(() => {
      if (this.data.scrollTop === e.detail.scrollTop) {
        this.setData({
          scrollTop: e.detail.scrollTop,
          isShowCart: true,
          showmenu: showmenu
        })
        clearTimeout(timer)
      }
    }, 3000);
  },
  //创建支付安卓手机,苹果手机发送申请(授权头像昵称)
  creatMyCardPay: function (e) {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      if (!isAccredit) {//弹出授权框且同意
        utils.AuthorizeUserInfoOld(e, that.data.loginCode);
      }
      that.toCreatMyCardPay();
    } else {
      utils.showToast('请授权微信头像、昵称');      
    }
  },

  //创建支付安卓手机,苹果手机发送申请(先授权微信头像昵称)===用户授权api修改
  creatMyCardPayByfile: function () {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.toCreatMyCardPay();
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        });
      },
      fail: (err) => {
        utils.showToast('请授权微信头像、昵称');       
      }
    })
  },

  //创建支付安卓手机,苹果手机发送申请
  toCreatMyCardPay: function (e) {
    var that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    if (that.data.versionid == 3) {
      that.createStaffPayRequest(that.data.versionid);
    } else {
      if (app.globalData.platform != 'ios' || that.data.versionid == 1) {
        wxpay.createStaffOrder(app, cardInfo.Id, that.data.versionid);
        utils.aiCardActionRecord(24);
      } else {
        //发送创建申请
        that.createStaffPayRequest(that.data.versionid);
      }
    }
  },

  //申请代付
  applyCardPay: function (e) {
    var that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      if (!isAccredit) {//弹出授权框且同意
        utils.AuthorizeUserInfoOld(e, that.data.loginCode);
      }
      that.createStaffPayRequest(that.data.versionid);
    } else {
      utils.showToast('请授权微信头像、昵称');
    }
  },

  //申请代付===用户授权api修改
  applyCardPayByfile: function () {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.createStaffPayRequest(that.data.versionid);
          }
        });
      },
      fail: (err) => {
        utils.showToast('请授权微信头像、昵称');
      }
    })
  },

  //申请代付
  createStaffPayRequest: function (versionid) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.showLoading({
      title: '申请中',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Staff/CreateStaffPayRequest?fromUid=' + app.globalData.userInfo.Uid + '&toUid=' + cardInfo.Uid + '&industryCode=' + versionid,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          utils.showToast('申请成功');
          that.dialogsState();
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  //是否登录
  isLogin: function(){
    let that = this;
    let isAccredit = that.data.isAccredit;
    let back = '/pages/product/classes/index';
    if(that.data.supplyUid>0){
      back += encodeURIComponent('?supplyUid=' + that.data.supplyUid + '&version=5');
    }
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后方可购买商品，是否确认登陆？',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/accredit/index?back=' + back,
            })
          }
        }
      })
      return false;
    }
    return true;
  },

  //用户点击右上角分享
  onShareAppMessage: function (e) {
    var that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    return {
      path: '/pages/classes-new/index?id=' + cardInfo.Id + '&source=2',
      success: function (res) {
        utils.showModal('转发成功');        
      }
    }
  },
  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    var cardInfo = that.data.cardInfo;
    var shareTitle = "";
    if (that.data.shareTitle) {
      shareTitle = that.data.shareTitle;
    } else {
      shareTitle = cardInfo.CardInfo.Company;
    }
    let imageUrl = '';
    if (cardInfo.CardInfo.Avater) {
      imageUrl = utils.formatAvater(cardInfo.CardInfo.Avater, 'https://static.711688.net.cn/upload/card/source/');
    } else {
      let avaters = cardInfo.Slides;
      if (avaters) {
        avaters = avaters.split(',');
        imageUrl = utils.formatAvater(avaters[0], 'https://static.711688.net.cn/upload/card/source/');
      }
    }
    return {
      title: shareTitle,
      query: 'id=' + cardInfo.CardInfo.Id + '&uid=' + app.globalData.userInfo.Uid + '&isFriendState=1',
      imageUrl: imageUrl
    }
  },

  // 连接socket监听聊天消息
  toChat: function () {
    let that = this;
    if (app.globalData.userInfo) {
      let uid = app.globalData.userInfo.Uid;
      setTimeout(() => {
        chat.initChat(uid, function(){
          //连接成功
        },
         function(){
            that.setData({msgLength: 1}); //新消息
        });
      }, 500);
    }
  },
    // 一键领取优惠券
    getCouponsHolder: function () {
      let that = this;
      let cardId = wx.getStorageSync('cardId');
      var couponTypeIds = '';
  
      if (that.data.isPackage == 0) {
        for (var i = 0; i < that.data.couponTypeList.length; i++) {
          let item = that.data.couponTypeList[i];
          couponTypeIds += item.coupontypeid + ",";
        }
        couponTypeIds = couponTypeIds.substr(0, couponTypeIds.length - 1);
      } else {
        couponTypeIds = '';
      }
  
      let isAccredit = that.data.isAccredit;
      if (!isAccredit) {
        let back = '/pages/index/index';
        wx.navigateTo({
          url: '../accredit/index?back=' + back + '&createUid=' + that.data.cardInfo.CardInfo.Uid + '&couponTypeIds=' + couponTypeIds
        })
      } else {
        wx.showLoading({title: '正在领取',mask: true})      
        wx.request({
          url: app.globalData.host + '/api/Coupon/AddUserPackage',
          data: {
            staffId: cardId,
            couponTypeIds: couponTypeIds,
            uid: app.globalData.userInfo.Uid,
            createUid: that.data.cardInfo.CardInfo.Uid
          },
          method: 'POST',
          success: function (res) {
            wx.hideLoading();
            if (res.data.Code == 0) {
              utils.showToast('领取成功');     
            } else {
              utils.showModal(res.data.Message);           
            }
          }
        })
        that.setData({isCoupon:false})
      }
    },
    
    showdialog: function(){
      this.setData({
        isCoupon: true
      })
    },
    // 关闭红包弹窗
    closedialog: function (e) {
      this.setData({
        isCoupon: false
      })
    },

  // 关于产品头图
  changeClassImg: function () {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      complete: function (res) {
        if (res.tempFilePaths) {
          wx.navigateTo({
            url: '/pages/weijieke/chooseImage/index?src=' + res.tempFilePaths[0] + '&height=100',
          })
        }
      }
    })
  },
  //产品列表头图上传
  staffAvatarUpload: function (imgsrc) {
    wx.showLoading({
      title: '上传中',
      mask: true,
    })
    var that = this;
    var url = app.globalData.host + '/api/tool/upload?operation=saveproducteditorimage&storeid=' + app.globalData.storeId;
    wx.uploadFile({
      url: url,
      filePath: imgsrc,
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        var avater = 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/' + JSON.parse(resp.data).Data;
        that.setProductBanner(avater);
      },
      fail: function (err) {
        utils.showModal(err.data.Message);        
      }
    })
  },
  setProductBanner: function (avater) {
    let that = this;
    let cardid = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/Staff/SetProductBanner?staffId=' + cardid + '&src=' + avater,
      success: function (res) {
        if (res.data.Code == 0) {
          that.getAiCardInfo();
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },
  //离开当前页面
  onUnload: function () {
    if (this.data.showmenu) {
      utils.toCloseSocket();
    }
  },
  onHide: function () {
    if (this.data.showmenu) {
      utils.toCloseSocket();
    }
  }
})